﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using System.Windows.Navigation;
using System.ComponentModel;
using System.Security.Cryptography;
using System.Configuration;
using System.ServiceModel;
using System.ServiceModel.Security;
using System.Security.Cryptography.X509Certificates;
using System.Windows.Media.Animation;

namespace TARADesktopDoctor
{
    public partial class LoginPage
    {
        //tara_wcf.ItaraServiceClient svc = new tara_wcf.ItaraServiceClient();

        #region variables for acs

        tara_wcf.ItaraService svc;
        public const string ServiceNamespace = "acstara";
        public const string AcsHostUrl = "accesscontrol.windows.net";
        static string ServiceAddress = "http://localhost:7100/taraService.svc";
        static string ServiceCertificateFilePath = ConfigurationManager.AppSettings.Get("ServiceCertificateFilePath");

        static string ClientUsername = ConfigurationManager.AppSettings.Get("ClientUsername");
        static string ClientPassword = ConfigurationManager.AppSettings.Get("ClientPassword");


        #endregion

        #region acs methods

        private static void TrustAllCertificates()
        {
            //Trust all certificates
            System.Net.ServicePointManager.ServerCertificateValidationCallback =
                ((sender, certificate, chain, sslPolicyErrors) => true);
        }

        private static ChannelFactory<tara_wcf.ItaraService> CreateChannelFactory(string acsUsernameEndpoint, string serviceEndpoint)
        {
            //
            // The WCF service endpoint host name may not match the service certificate subject.
            // By default, the host name is 'localhost' and the certificate subject is 'WcfServiceCertificate'.
            // Create a DNS Endpoint identity to match WcfServiceCertificate.
            //
            EndpointAddress serviceEndpointAddress = new EndpointAddress(new Uri(serviceEndpoint),
                                                                          EndpointIdentity.CreateDnsIdentity(GetServiceCertificateSubjectName()));

            ChannelFactory<tara_wcf.ItaraService> stringServiceFactory = new ChannelFactory<tara_wcf.ItaraService>(Bindings.CreateServiceBinding(acsUsernameEndpoint), serviceEndpointAddress);

            // Set the service credentials and disable certificate validation to work with sample certificates
            stringServiceFactory.Credentials.ServiceCertificate.Authentication.CertificateValidationMode = X509CertificateValidationMode.None;
            stringServiceFactory.Credentials.ServiceCertificate.DefaultCertificate = GetServiceCertificate();

            // Set the client credentials.
            stringServiceFactory.Credentials.UserName.UserName = ClientUsername;
            stringServiceFactory.Credentials.UserName.Password = ClientPassword;

            return stringServiceFactory;
        }

        private static X509Certificate2 GetServiceCertificate()
        {
            return new X509Certificate2(ServiceCertificateFilePath);
        }

        private static string GetServiceCertificateSubjectName()
        {
            const string cnPrefix = "CN=";
            string subjectFullName = GetServiceCertificate().Subject;
            System.Diagnostics.Debug.Assert(subjectFullName.StartsWith(cnPrefix));
            return subjectFullName.Substring(cnPrefix.Length);
        }


        #endregion

        public LoginPage()
        {
            this.InitializeComponent();

            /*Hard-Coded Login for easy access*/
            //tbxUsername.Text = "test";
            //pbxPassword.Password = "test";
            tbxUsername.Focus();// = true;
            
            //#region acs implementation

            ////new service
            //TrustAllCertificates();

            //string acsUsernameEndpoint = String.Format("https://{0}.{1}/v2/wstrust/13/username", ServiceNamespace, AcsHostUrl);

            //ChannelFactory<tara_wcf.ItaraService> stringServiceFactory = CreateChannelFactory(acsUsernameEndpoint, ServiceAddress);
            //svc = stringServiceFactory.CreateChannel();
            //ICommunicationObject channel = (ICommunicationObject)svc;


            //#endregion


        }
        Storyboard loading1;
        private void btnLogin_Click(object sender, RoutedEventArgs e)
        {
        
            doc = Login(tbxUsername.Text, Hash(pbxPassword.Password));
            if (doc != null)
            {
                //set up backgroundworker
                BackgroundWorker bgWorker = new BackgroundWorker();
                bgWorker.DoWork += new DoWorkEventHandler(bgWorker_DoWork);
                bgWorker.RunWorkerCompleted += new RunWorkerCompletedEventHandler(bgWorker_RunWorkerCompleted);
                bgWorker.WorkerSupportsCancellation = true;

                //run background worker
                bgWorker.RunWorkerAsync(500);
            }
            else
            {
                MessageBox.Show("Wrong Username or Password");//Login Failed
            }
        }

        void bgWorker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            NavigationService.Navigate(new PatientSelectionPage(doc));
        }

        void bgWorker_DoWork(object sender, DoWorkEventArgs e)
        {
            //throw new NotImplementedException();

            //Dispatcher.BeginInvoke((Action) =>
            //{

            //});
        }

        public static tara_wcf.doctor doc = new tara_wcf.doctor();
        private void tbxUsername_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.Key == Key.Enter)
            {
                doc = Login(tbxUsername.Text, Hash(pbxPassword.Password));
                if (doc != null)
                {
                    //set up backgroundworker
                    BackgroundWorker bgWorker = new BackgroundWorker();
                    bgWorker.DoWork += new DoWorkEventHandler(bgWorker_DoWork);
                    bgWorker.RunWorkerCompleted += new RunWorkerCompletedEventHandler(bgWorker_RunWorkerCompleted);
                    bgWorker.WorkerSupportsCancellation = true;

                    //run background worker
                    bgWorker.RunWorkerAsync(500);
                }
                else
                {
                    if (noConnection == false)
                    {
                        MessageBox.Show("Wrong Username or Password");//Login Failed
                    }
                }
            }
        }

        private void pbxPassword_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.Key == Key.Enter)
            {
                doc = Login(tbxUsername.Text, Hash(pbxPassword.Password));
                if (doc != null)
                {
                    //set up backgroundworker
                    BackgroundWorker bgWorker = new BackgroundWorker();
                    bgWorker.DoWork += new DoWorkEventHandler(bgWorker_DoWork);
                    bgWorker.RunWorkerCompleted += new RunWorkerCompletedEventHandler(bgWorker_RunWorkerCompleted);
                    bgWorker.WorkerSupportsCancellation = true;

                    //run background worker
                    bgWorker.RunWorkerAsync(500);
                }
                else
                {
                    if (noConnection == false)
                    {
                        MessageBox.Show("Wrong Username or Password");//Login Failed
                    }
                }
            }
        }

        #region Local Login Methods
        private string Hash(string ToHash)
        {
            // First we need to convert the string into bytes, which means using a text encoder.
            Encoder enc = System.Text.Encoding.ASCII.GetEncoder();

            // Create a buffer large enough to hold the string
            byte[] data = new byte[ToHash.Length];
            enc.GetBytes(ToHash.ToCharArray(), 0, ToHash.Length, data, 0, true);

            SHA1 sha1 = new SHA1CryptoServiceProvider();
            byte[] result = sha1.ComputeHash(data);

            return BitConverter.ToString(result).Replace("-", "");
        }

        bool noConnection = false;
        private tara_wcf.doctor Login(string username, string password)
        {
            string Key, ToHash;
            try
            {
                string Token = svc.GetToken();
                ToHash = username + "|" + password + "|" + Token;
                Key = Hash(ToHash) + "|" + username + "|I would like to log this string in a DB";

                return svc.DocUseService(Key);
            }
            catch (Exception ex)
            {
                noConnection = true;
                MessageBox.Show("Kindly Check Connection");
            }
            return null;
        }
        #endregion
    }
}